import React from "react";

import {TextInput} from "react-native";
import PropTypes from 'prop-types';

class AutoExpandingInput extends React.PureComponent {

  constructor(props) {
    super(props);
    this.state = { height: props.initialHeight };
  }

  focus(){
    this.input && this.input.focus();
  }

  blur(){
    this.input && this.input.blur();
  }

  onContentSizeChange(event) {
    this.setState({ height: event.nativeEvent.contentSize.height });
  }

  render() {
    const { style, ref, multiline, blurOnSubmit, ...props } = this.props;
    return (
        <TextInput {...props}
                   ref={v=>this.input=v}
                   blurOnSubmit
                   multiline={multiline}
                   onContentSizeChange={this.onContentSizeChange.bind(this)}
                   style={{ minHeight: this.props.initialHeight, maxHeight: this.props.maxHeight, height: Math.min(this.props.maxHeight, this.state.height), ...style }}
        />
    );
  }
}
AutoExpandingInput.propTypes = {
  maxHeight: PropTypes.number,
  initialHeight: PropTypes.number,
  blurOnSubmit: PropTypes.bool,
  multiline: PropTypes.bool
};

AutoExpandingInput.defaultProps = {
  maxHeight: 40,
  initialHeight: 26,
  multiline: true,
  blurOnSubmit: true
};

export default AutoExpandingInput;
